package com.travel.service;

import com.travel.constants.ShiroConstants;
import com.travel.exception.user.UserPasswordNotMatchException;
import com.travel.model.SysUser;
import com.travel.model.WebUser;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class WebPasswordService {
    @Autowired
    private CacheManager cacheManager;

    private Cache<String, AtomicInteger> loginRecordCache;

    @PostConstruct
    public void init() {
        loginRecordCache = cacheManager.getCache(ShiroConstants.LOGINRECORDCACHE);
    }

    public void validate(WebUser user, String password) {
        String emial = user.getEmail();
        if (!matches(user, password)) {
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(emial);
        }
    }

    public boolean matches(SysUser user, String newPassword) {
        return user.getPassword().equals(encryptPassword(user.getLoginName(), newPassword, user.getSalt()));
    }

    public boolean matches(WebUser user, String newPassword) {
        return user.getPassword().equals(newPassword);
    }

    public void clearLoginRecordCache(String loginName) {
        loginRecordCache.remove(loginName);
    }

    public String encryptPassword(String loginName, String password, String salt) {
        return new Md5Hash(loginName + password + salt).toHex();
    }
}
